package com.na.game.resource;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Typeface;

import com.na.game.GameActivity;
import com.na.game.GameManager;
import com.na.game.GameManager.Clazz;
import com.na.game.graphics.Image;
import com.na.game.opengl.GLImage;
import com.na.game.util.GameConfig;
import com.na.game.util.Util;

public class ResourceManager implements Destruction, Clazz {

	private Map<String, Image> cache = new HashMap<String, Image>();
	private Map<String, Typeface> typefaceCache = new HashMap<String, Typeface>();
	
	public InputStream getAssets(String fileName) {
		synchronized (fileName) {
			return Util.getAssets(fileName);
		}
	}
	
	public Image getImageFromAssets(String fileName) {
		synchronized (fileName) {
			Image image = cache.get(fileName);
			if (image != null && !image.isRecycled()) {
				return image;
			}
			InputStream in = getAssets(fileName);
			if (in != null) {
				Options op = new Options();
				op.inPreferredConfig = Config.ARGB_8888;
				Bitmap bitmap = BitmapFactory.decodeStream(in, null, op);
				image = GameConfig.useOpenGL ? new GLImage(bitmap, fileName) : new Image(bitmap, fileName);
				cache.put(fileName, image);
				try {
					in.close();
				} catch (IOException e) {
				}
				return image;
			}
			return null;
		}
	}
	
	public Typeface getTypefaceFromAssets(String fileName) {
		Typeface typeface = typefaceCache.get(fileName);
		if (typeface != null) {
			return typeface;
		}
		typeface = Typeface.createFromAsset(GameManager.get(GameActivity.class).getAssets(), fileName);
		typefaceCache.put(fileName, typeface);
		return typeface;
	}
	
	@Override
	public void destroy() {
		Collection<Image> values = cache.values();
		for (Image image : values) {
			image.destroy();
		}
		cache.clear();
	}

	@Override
	public Class<?> getClazz() {
		return getClass();
	}
	
}
